package com.tfkj.contrller;


import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.tfkj.service.AllService;
import com.tfkj.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@CrossOrigin(maxAge = 3600)
@RequestMapping("/rel")
@Api(value = "错题", tags = "错题接口")
public class StudentImageRelController {

    @Autowired
    private AllService allService;

    @ApiOperation("创建学生错题关系")
    @PostMapping("/create")
    public CommonReturn createRel(@RequestBody InsertRelVO rel) {
        System.out.println(rel.toString());
        allService.insertStudentImageRel(rel);
        return new CommonReturn(200, "添加成功！");
    }

    @ApiOperation("更新学生错题关系")
    @PostMapping("/update")
    public CommonReturn createRel(@RequestBody UpdateRelVO vo) {
        allService.updateStudentImageRel(vo.getIsError(), vo.getId());
        return new CommonReturn(200, "添加成功！");
    }

    @ApiOperation("删除学生错题关系")
    @PostMapping("/delete/{id}")
    public CommonReturn createRel(@PathVariable("id") Integer id) {
        allService.deleteStudentImageRel(id);
        return new CommonReturn(200, "删除成功！");
    }

    @ApiOperation("查询学生错题关系")
    @PostMapping("/listError")
    public CommonReturn list(@RequestBody RelQueryVO vo) {
        List<String> questionTypes = null;
        if (vo.getQuestionType() != null && "".equals(vo.getQuestionType())) {
            questionTypes = Arrays.asList(vo.getQuestionType().split(","));
        }
        List<RelShowVO> list = allService.findErrorList(vo.getStudentNum(), vo.getGrade(), vo.getClassName(), vo.getSubject(), questionTypes, vo.getDifficulty(), vo.getPageNum(), vo.getPageSize(), vo.getStartTime(), vo.getEndTime());
        Integer total = allService.findErrorListTotal(vo.getStudentNum(), vo.getGrade(), vo.getClassName(), vo.getSubject(), questionTypes, vo.getDifficulty(), vo.getStartTime(), vo.getEndTime());
        return new CommonReturn(list,total);
    }


    @PostMapping("/upload")
    public CommonReturn uploadExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new CommonReturn(500,"请选择要上传的文件");
        }

        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            List<ExcelUploadVO> uploadVOS = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第二行开始
                ExcelUploadVO uploadVO = new ExcelUploadVO();
                Row row = sheet.getRow(i);
                if (row == null) continue;
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    String value = getCellValueAsString(cell);
                    switch (j){
                        case 1:
                            uploadVO.setStudentNUm(value);
                            break;
                        case 4:
                            uploadVO.setTestNum(value);
                            break;
                        case 5:
                            uploadVO.setVos(parseBracketStrings(value));
                            break;
                        default:
                            break;
                    }
                }
                uploadVOS.add(uploadVO);

            }
            if (uploadVOS.isEmpty()){
                return new CommonReturn(200,"未解析到数据");
            }
            allService.relUpload(uploadVOS);
            return new CommonReturn(200,"文件解析完成，请查看控制台输出");
        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
            return new CommonReturn(500,"文件处理失败: " + e.getMessage());
        } catch (Exception e) {

            e.printStackTrace();
            return new CommonReturn(500,"系统错误: " + e.getMessage());
        }
    }
    public String getCellValueAsString(Cell cell) {
        if (cell == null) return null;

        DataFormatter formatter = new DataFormatter();
        String value = formatter.formatCellValue(cell);

        // 处理科学计数法污染（如身份证号）
        if (cell.getCellType() == CellType.NUMERIC
                && value.matches("\\d+\\.0$")) {
            value = value.replace(".0", "");
        }

        return value.trim();
    }

    public static List<ExcelRelVO> parseBracketStrings(String rawStr) {
        // 预处理字符串：替换中文符号 + 去除首尾空格
        String processed = rawStr.replaceAll("（", "(")
                .replaceAll("）", ")")
                .replaceAll("，", ",")
                .trim();

        // 分割外层括号结构
        String[] segments = processed.split("\\)\\("); // 支持括号间的空格

        List<ExcelRelVO> result = new ArrayList<>();
        for (String segment : segments) {
            // 去除首尾残留括号（处理第一个和最后一个元素）
            String cleanSegment = segment.replaceAll("\\(", "")
                    .replaceAll("\\)", "")
                    .trim();
            if (cleanSegment.isEmpty()) continue;

            // 分割内部字段
            String[] parts = cleanSegment.split("\\s*,\\s*", 3); // 限制分割3部分

            if (parts.length != 3) {
                System.err.println("格式错误: " + cleanSegment);
                continue;
            }

            try {
                result.add(new ExcelRelVO(
                        Integer.parseInt(parts[0].trim()),
                        parts[1].trim(),
                        parts[2].trim()
                ));
            } catch (NumberFormatException e) {
                System.err.println("页码转换失败: " + cleanSegment);
            }
        }
        return result;
    }
}
